package com.itcast.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.itcast.constant.MessageConstant;
import com.itcast.entity.Result;
import com.itcast.mapper.SetmealMapper;
import com.itcast.pojo.CheckGroup;
import com.itcast.pojo.CheckItem;
import com.itcast.pojo.Setmeal;
import com.itcast.service.SetmealService;
import com.itcast.vo.CheckGroupVo;
import com.itcast.vo.GroupAndItem;
import com.qiniu.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceimpl implements SetmealService {
    @Autowired
    SetmealMapper setmealMapper;
    @Autowired
    JedisPool jedisPool;

    @Override
    public Result getSetmeal() {
        String setmeal = jedisPool.getResource().get("setmeal");
        try {
            if (null == setmeal) {
                List<Setmeal> setmeals = setmealMapper.getSetmeal();
               /* HashMap<String, List<Setmeal>> map = new HashMap<>();
                map.put("data",setmeals);*/
                String json = JSON.toJSONString(setmeals);
                //存入redis
                jedisPool.getResource().set("setmeal", json);
                //返回数据
                return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmeals);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);

        }
        //json 字符串转换为对象
        Object parse = JSON.parse(setmeal);
        //返回数据
        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, parse);
    }

    @Override
    public Setmeal findByid(Integer id) {
        /*
      {setmeal.name}}   {setmeal.remark} {setmeal.sex} {setmeal.age}
      {checkgroup.name} {checkgroup.remark}}
      {checkitem.name}}
       */
        //通过套餐id 获取套餐详情
        Setmeal setmeal = setmealMapper.findSetmealById(id);
        //通过 套餐和项目组表 获取 项目组id
        List<CheckGroup> groupids = setmealMapper.findGroupAndSetmealById(id);
        //通过 groupids 获取 项目名
        for (CheckGroup groupid : groupids) {
            List<CheckItem> checkItems = setmealMapper.findItemNameByGroupId(groupid.getId());
            groupid.setCheckItems(checkItems);
        }
        setmeal.setCheckGroups(groupids);
        return setmeal;
    }


}
